package com.cn.demo4.servlet;

import com.alibaba.fastjson.JSONObject;
import com.cn.demo4.model.UserModel;
import com.cn.demo4.service.IUserService;
import com.cn.demo4.service.impl.UserServiceImpl;
import com.sun.org.apache.bcel.internal.generic.FASTORE;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置字符编码格式
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        //2.拿到前台的数据
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        //前台输入的验证码
        String code = req.getParameter("code");
        //后台存入session的验证码,因为时session对象，所以要强制转换为String
        String sessionCode = (String) req.getSession().getAttribute("code");

        //3.封装数据
        UserModel userModel = new UserModel();
        userModel.setPhone(phone);
        userModel.setPassword(password);
        userModel.setCode(code);
        userModel.setSessionCode(sessionCode);

        //4.调用服务层
        IUserService iUserService = new UserServiceImpl();

        //5.得到数据
        String result = iUserService.login(userModel);
        if("success".equals(result)){
            req.getSession().setAttribute(phone,phone);
        }
        UserModel model = iUserService.findByPhone(phone);
//        System.out.println(model);
        //6.返回结果
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        jsonObject.put("model", model);
        resp.getWriter().println(jsonObject);


    }
}
